import { useState, useEffect } from 'react';
import dayjs from 'dayjs';
import { Dialog } from '@headlessui/react';
import { Cog6ToothIcon } from '@heroicons/react/24/outline';
import { Calendar } from './components/Calendar';
import type { DayMark, TargetDate } from './types';
import Joyride, { Status } from 'react-joyride';

// 本地存储的键名
const STORAGE_KEYS = {
  TARGET_DATE: 'countdown-target',
  MARKS: 'countdown-marks'
};

export default function App() {
  // 控制设置弹窗的显示状态
  const [isSettingOpen, setIsSettingOpen] = useState(false);

  // 目标日期相关信息，从本地存储初始化
  const [targetDate, setTargetDate] = useState<TargetDate>(() => {
    const saved = localStorage.getItem(STORAGE_KEYS.TARGET_DATE);
    return saved ? JSON.parse(saved) : { startDate: '', endDate: '', title: '' };
  });

  // 日期标记数据，从本地存储初始化
  const [marks, setMarks] = useState<DayMark[]>(() => {
    const saved = localStorage.getItem(STORAGE_KEYS.MARKS);
    return saved ? JSON.parse(saved) : [];
  });

  // 剩余天数
  const [daysLeft, setDaysLeft] = useState(0);

  // 添加引导状态
  const [showGuide, setShowGuide] = useState(() => {
    return !localStorage.getItem('guide-completed');
  });

  // 引导步骤配置
  const [stepIndex, setStepIndex] = useState(0);

  // 强制更新状态
  const [forceUpdate, setForceUpdate] = useState(0);

  // 计算剩余天数：总天数 - 已完成天数
  useEffect(() => {
    if (targetDate.startDate && targetDate.endDate) {
      const totalDays = dayjs(targetDate.endDate).diff(dayjs(targetDate.startDate), 'day');
      const completedDays = marks.filter(mark => mark.status === 'check').length;
      setDaysLeft(totalDays - completedDays);
    }
  }, [targetDate.startDate, targetDate.endDate, marks]);

  // 目标日期信息变更时，保存到本地存储
  useEffect(() => {
    localStorage.setItem(STORAGE_KEYS.TARGET_DATE, JSON.stringify(targetDate));
  }, [targetDate]);

  // 标记数据变更时，保存到本地存储
  useEffect(() => {
    localStorage.setItem(STORAGE_KEYS.MARKS, JSON.stringify(marks));
  }, [marks]);

  // 添加自动进入下一步的效果
  useEffect(() => {
    if (!showGuide) return;

    // 检查当前步骤是否满足条件
    let canProceed = false;
    switch (stepIndex) {
      case 1:
        canProceed = isSettingOpen;
        break;
      case 2:
        canProceed = dayjs(targetDate.startDate).isSame(dayjs().subtract(1, 'day'), 'day');
        break;
      case 3:
        canProceed = dayjs(targetDate.endDate).month() === 9 &&
          dayjs(targetDate.endDate).date() === 1;
        break;
      case 4:
        canProceed = targetDate.title === '国庆节';
        break;
      case 5:
        canProceed = !isSettingOpen;
        break;
      case 7:
        canProceed = marks.some(m =>
          dayjs(m.date).isSame(dayjs(), 'day') &&
          m.status === 'check'
        );
        break;
    }

    if (canProceed) {
      setStepIndex(prev => prev + 1);
    }
  }, [showGuide, stepIndex, isSettingOpen, targetDate, marks]);

  // 处理日期标记状态变更
  const handleMarkDay = (date: string, status: 'check' | null) => {
    setMarks(prev => {
      const filtered = prev.filter(m => m.date !== date);
      if (status === null) return filtered;
      return [...filtered, { date, status }];
    });
  };

  // 修改步骤配置，添加验证函数
  const getSteps = () => [
    {
      target: '[data-guide="title"]',
      content: '欢迎使用倒数日历！让我们来设置一个纪念日吧，比如国庆节。',
      disableBeacon: true,
    },
    {
      target: '[data-guide="settings-button"]',
      content: '点击设置按钮，我们来设置国庆节倒计时。',
      spotlightClicks: true,
      disableBeacon: true,
    },
    {
      target: '[data-guide="start-date"]',
      content: '选择昨天作为开始日期',
      spotlightClicks: true,
      disableBeacon: true,
    },
    {
      target: '[data-guide="target-date"]',
      content: '选择 10 月 1 日作为目标日期',
      spotlightClicks: true,
      disableBeacon: true,
      placement: 'left',
    },
    {
      target: '[data-guide="title-input"]',
      content: '输入目标标题：国庆节',
      spotlightClicks: true,
      disableBeacon: true,
    },
    {
      target: '[data-guide="close-model"]',
      content: '点击关闭',
      spotlightClicks: true,
      disableBeacon: true,
    },
    {
      target: '[data-guide="countdown"]',
      content: '看看还有多少天？',
      disableBeacon: true,
    },
    {
      target: '[data-guide="calendar"]',
      content: '在日历上点击今天的日期，标记为已完成。',
      spotlightClicks: true,
      disableBeacon: true,
    }
  ];

  const handleJoyrideCallback = (data: { status: Status; type: string; index: number; action: string }) => {
    const { status, type, index } = data;

    if (status === 'finished') {
      setShowGuide(false);
      localStorage.setItem('guide-completed', 'true');
      return;
    }

    if (type === 'step:after') {
      if (index === 0) {
        setStepIndex(1);
        return;
      }

      let canProceed = true;
      switch (index) {
        case 1:
          canProceed = isSettingOpen;
          break;
        case 2:
          canProceed = dayjs(targetDate.startDate).isSame(dayjs().subtract(1, 'day'), 'day');
          break;
        case 3:
          canProceed = dayjs(targetDate.endDate).month() === 9 &&
            dayjs(targetDate.endDate).date() === 1;
          break;
        case 4:
          canProceed = targetDate.title === '国庆节';
          break;
        case 5:
          canProceed = !isSettingOpen;
          break;
        case 7:
          canProceed = marks.some(m =>
            dayjs(m.date).isSame(dayjs(), 'day') &&
            m.status === 'check'
          );
          break;
      }

      if (canProceed) {
        setStepIndex(index + 1);
      } else {
        // 强制更新当前步骤
        setForceUpdate(prev => prev + 1);
      }
    }
  };

  return (
    <div className="min-h-screen bg-gray-50 py-8 px-4">
      <Joyride
        key={forceUpdate}
        steps={getSteps() as Array<{
          target: string;
          content: string;
          disableBeacon: boolean;
          spotlightClicks?: boolean;
          placement?: 'auto' | 'top' | 'top-start' | 'top-end' | 'bottom' |
          'bottom-start' | 'bottom-end' | 'left' | 'left-start' | 'left-end' |
          'right' | 'right-start' | 'right-end' | 'center';
        }>}
        stepIndex={stepIndex}
        run={showGuide}
        continuous
        showProgress
        hideBackButton
        disableOverlayClose={true}
        spotlightClicks={true}
        styles={{
          options: {
            primaryColor: '#3b82f6',
            zIndex: 10000,
          },
          overlay: {
            height: '100%',
          },
          tooltip: {
            zIndex: 10001,
          },
        }}
        callback={handleJoyrideCallback}
        locale={{
          close: '关闭',
          last: '完成',
          next: '下一步'
        }}
      />

      <div className="max-w-4xl mx-auto">
        <div className="bg-white rounded-lg shadow p-6 mb-6">
          <div className="flex justify-between items-center mb-6">
            <h1 data-guide="title" className="text-2xl font-bold">倒数日历</h1>
            <button
              data-guide="settings-button"
              onClick={() => setIsSettingOpen(true)}
              className="flex items-center gap-2 px-4 py-2 text-sm font-medium text-gray-700 bg-gray-100 rounded-md hover:bg-gray-200"
            >
              <Cog6ToothIcon className="w-5 h-5" />
              设置
            </button>
          </div>

          {targetDate.startDate && targetDate.endDate && (
            <div data-guide="countdown" className="text-center mb-6">
              <h2 className="text-xl font-semibold">{targetDate.title}</h2>
              <p className="text-3xl font-bold text-blue-600 mt-2">
                还需 {daysLeft} 天
              </p>
            </div>
          )}

          <div data-guide="calendar">
            <Calendar
              startDate={targetDate.startDate}
              targetDate={targetDate.endDate}
              marks={marks}
              onMarkDay={handleMarkDay}
            />
          </div>

          <Dialog
            open={isSettingOpen}
            onClose={() => {
              if (!showGuide) {
                setIsSettingOpen(false);
              }
            }}
            className="relative z-[9999]" // 调整弹窗层级
          >
            <div className="fixed inset-0 bg-black/30" aria-hidden="true" />

            <div className="fixed inset-0 flex items-center justify-center p-4">
              <Dialog.Panel className="mx-auto max-w-md rounded-lg bg-white p-6 shadow-xl">
                <Dialog.Title className="text-lg font-medium mb-4">
                  目标设置
                </Dialog.Title>

                <div className="space-y-4">
                  <div className="bg-blue-50 p-4 rounded-lg border-2 border-blue-200">
                    <label className="block text-sm font-bold text-blue-700 mb-2">
                      开始日期
                    </label>
                    <input
                      type="date"
                      data-guide="start-date"
                      value={targetDate.startDate}
                      onChange={e => setTargetDate(prev => ({ ...prev, startDate: e.target.value }))}
                      className="border-2 border-blue-300 rounded px-3 py-2 w-full bg-white focus:border-blue-500 focus:ring-2 focus:ring-blue-200"
                    />
                  </div>

                  <div className="bg-green-50 p-4 rounded-lg border-2 border-green-200">
                    <label className="block text-sm font-bold text-green-700 mb-2">
                      目标日期
                    </label>
                    <input
                      type="date"
                      data-guide="target-date"
                      value={targetDate.endDate}
                      onChange={e => setTargetDate(prev => ({ ...prev, endDate: e.target.value }))}
                      className="border-2 border-green-300 rounded px-3 py-2 w-full bg-white focus:border-green-500 focus:ring-2 focus:ring-green-200"
                    />
                  </div>

                  <div>
                    <label className="block text-sm font-medium text-gray-700 mb-2">
                      目标标题
                    </label>
                    <input
                      type="text"
                      data-guide="title-input"
                      value={targetDate.title}
                      onChange={e => setTargetDate(prev => ({ ...prev, title: e.target.value }))}
                      placeholder="为目标添加标题"
                      className="border rounded px-3 py-2 w-full"
                    />
                  </div>
                </div>

                <div className="mt-6 flex justify-end gap-3">
                  <button
                    data-guide="close-model"
                    onClick={() => setIsSettingOpen(false)}
                    className="px-4 py-2 text-sm font-medium text-gray-700 bg-gray-100 rounded-md hover:bg-gray-200"
                  >
                    关闭
                  </button>
                </div>
              </Dialog.Panel>
            </div>
          </Dialog>
        </div>
      </div>
    </div>
  );
}